﻿using UnityEngine;
using System.Collections.Generic;
using Dict.DataModel;
namespace Room
{
    public class RCAIPatrolNPC : RCAIBase
    {

        public string npcId;
        public float totalTime;
        private List<Dict.DataModel.TablePatrol> path;
        private int curIndex;
        private float lastStartTime;
        public RCAIPatrolNPC(RoomCharactor owner)
            :base(owner)
        {
            type = AIType.PatrolNPC;
        }

        public void Init(string npcId)
        {
            this.npcId = npcId;
            path = Dict.DictDataManager.Instance.tablePatrolDao.GetByOneIndex(npcId);
            totalTime = 0;
            for(int i=0;i<path.Count;i++)
            {
                totalTime += (float)path[i].time;
            }
        }

        public override void DoStart()
        {
            DataMessageTool.AddHandler(DataMessage.ROOM_SELF_CREATED, OnSelfCreated);
        }
        public override void DoStop()
        {
            DataMessageTool.RemoveHandler(DataMessage.ROOM_SELF_CREATED, OnSelfCreated);
        }
        private void OnSelfCreated(object obj)
        {
            DoResume();
        }
        public override void DoResume()
        {
            if (path.Count == 0)
                return;
            long serverTime = ServerTimerTool.CurrentUTCJavaTime();
            long totalLongTime = (long)(totalTime * 1000);

            float curTime = ((serverTime % totalLongTime) / 1000f);
            curTime = (curTime + (float)path[0].offsetTime) % totalTime;


            curIndex = GetIndex(curTime);
            var pos = GetPosition(curTime);
            float subTime = curTime % totalTime;
            for(int i=0;i<curIndex;i++)
            {
                subTime -= (float)path[i].time  ;
            }

            var nextIndex = (curIndex+1) % path.Count;
            var nextData = path[nextIndex];
            var nextVector = new Vector3((float)nextData.x, (float)nextData.y, (float)nextData.z);

            var speed = (nextVector- pos).magnitude/((float)path[curIndex].time - subTime);
            if(speed<0)
            {
                speed = 1;
            }
            owner.StopMove();
            (owner.move as RCMoveNavigation).usingNavAgent = false;
            owner.transform.position = pos;
            (owner.move as RCMoveNavigation).usingNavAgent = true;
            owner.SetSpeed(speed);
            owner.StopTo(nextVector);
            owner.PlayAnim("run");

            lastStartTime = Time.unscaledTime - subTime;
        }

        public override void Tick()
        {
            if (path.Count == 0)
                return;
            if (!owner.IsMoving())
            {
                var curData= path[curIndex];
                int nextIndex = (curIndex + 1 ) % path.Count;
                int targetIndex = (nextIndex + 1) % path.Count;

                var nextData = path[nextIndex];
                var targetData = path[targetIndex];
                                                 
                var targetVector = new Vector3((float)targetData.x, (float)targetData.y, (float)targetData.z);

                float time = (float)(curData.time + nextData.time) - (Time.unscaledTime - lastStartTime);
                float speed = (owner.transform.position - targetVector).magnitude / time;
                if (speed < 1)
                    speed = 1;
                if (speed > 2)
                    speed = 2;
                owner.SetSpeed(speed);
                owner.StopTo(targetVector);
                curIndex = nextIndex;

                lastStartTime = Time.unscaledTime;
            }
        }
        
        private Vector3 GetPosition()
        {
            long serverTime = ServerTimerTool.CurrentUTCJavaTime();

            float curTime = ((serverTime % totalTime) / 1000f);

            return GetPosition(curTime);
        }
        private Vector3 GetPosition(float time)
        {
            time = time % totalTime;
            TablePatrol start=null, end=null;
            
            var index = GetIndex(time);
            start = path[index];
            end = path[(index + 1) % path.Count];

            float subTime = time; ;
            for (int i=0;i<index; i++)
            {
                subTime -= (float)path[i].time;
            }
            Vector3 v0 = new Vector3((float)start.x, (float)start.y, (float)start.z);
            Vector3 v1 = new Vector3((float)end.x, (float)end.y, (float)end.z);
            return (v1 - v0) * (subTime / (float)start.time) + v0;
        }
        private int GetIndex(float time)
        {
            time = time % totalTime;
            float sumTime = 0f;
            for (int i = 0; i < path.Count; i++)
            {
                if (time <= sumTime + path[i].time)
                {
                    return i;
                }
                sumTime += (float)path[i].time;
            }
            return 0;
        }
    }

}

